#include "user_threads.h"
#include "tests.h"

int arr[3];
uthread_mutex_t print_mutex;

static void print_to_screen(char* str)
{
	int count = 0,writed = 0;
	int len = strlen(str);
	while (count != len) {
		writed = uthread_write(1,str+count,sizeof(char)*(len-count));
		if (writed	>=	0)
			count += writed;
	}
	return;
}

static char* itoa(int num)
{
	if	(num == 0) 
		return "0";
	int num_digits=0,i=1;
	while (i <= num) {
		num_digits++;
		i *= 10;
	}
	char* str = (char*)malloc((num_digits+1)*sizeof(char));
	char tmp;
	str[num_digits] = '\0';
	for (i = (num_digits-1); i >= 0; i--){
		tmp = (char)(num % 10) + '0';
		num /= 10;
		str[i] = tmp;
	}
	return str;
}

static void block(uthread_mutex_t mutex) 
{
	if (uthread_mutex_lock(mutex) != MUTEX_SUCCESS) {
		print_to_screen("Unable to lock mutex.\n");
		exit(-1);
	}
}

static void unblock(uthread_mutex_t mutex) 
{
	if (uthread_mutex_unlock(mutex) != MUTEX_SUCCESS) {
		print_to_screen("Unable to unlock mutex.\n");
		exit(-1);
	}
}

static inline void delay(int n, char c) {
	int i;
	for (i = 0 ; i < n ; i++)
		i=i;
}

static inline void reset_counter()
{
	counter = 0;
}

static void msg_with_expected_order(int i, char * in, int id){
		block(print_mutex);
		print_to_screen(itoa(i));
	  print_to_screen(": ");
		print_to_screen("Thread Id= ");
		print_to_screen(itoa(id));
		print_to_screen("   ");
		print_to_screen(in);
		print_to_screen("\n");
		unblock(print_mutex);
}

static void msg(char * in){
	msg_with_expected_order(1,in,uthread_self());
}
int ff(void* arg)
{
	int i=0;
	for(i=0;i<100;i++){}
	uthread_join(arr[1],arg);
	return (uthread_self());
}
int ff1(void* arg)
{
	int i=0;
	for(i=0;i<100;i++){}
	uthread_join(arr[2],arg);
	return (uthread_self());
}
int ff2(void* arg)
{
	int i=0;
	for(i=0;i<100;i++){}
	uthread_exit(9);
	return (uthread_self());
}


int test8()
{
	reset_counter();
	msg("\n*****************Running test #8...************\n");
	
	arr[0]=uthread_create(ff,NULL);
	arr[1]=uthread_create(ff1,NULL);
	arr[2]=uthread_create(ff2,NULL);
	
	uthread_yield();
	
	assert(uthread_cancel(arr[0]) == UTHREAD_SUCCESS);
	
	uthread_join(arr[0],NULL);
	int i;
	for(i=0;i<1000000000;i++);
	for(i=0;i<1000000000;i++);
	for(i=0;i<1000000000;i++);

	return 0;
}
